# coding: utf-8
# @Author: cyl
# @File: 08进阶2.py
# @Time: 2024/07/08 20:55:02


"""函数内容调用自身"""
def calc(n):
    print(n)
    if int(n / 2) == 0:
        return n
    return calc(int(n / 2))


calc(10) # 10 5 2 1

'''
    递归特性
        1. 必须有一个明确的`结束`条件
        2. 每次进入更深一层的递归时 问题规模相比上次递归都应有所减少
        3. 递归效率不高 递归层次过多会导致栈(stack)溢出 这种数据结构实现时 每当进入一个函数调用 栈就会加一层栈帧
           每当函数返回 栈就会减少一层栈帧, 由于栈的大小不是无限的 所以函数调用的次数过多 会导致栈溢出
'''

# 斐波那契: 斐波那契数列（Fibonacci sequence）, 又称黄金分割数列, 指的是这样一个数列：0、1、1、2、3、5、8、13、21、34、……。
# 使用递归
def fib(n):
    if n==1 or n==2:
        return 1
    return fib(n-1) + fib(n-2)

print(fib(10)) # 55


"""
列表推导式
a: list = [i for i in iterable]
等价于
abc: list = [1, 2, 3, 4, 5, 6]
for i in abc:
    print(i)
"""

# 场景: 过滤掉>5的数据
request_data: list = [1, 2, 3, 4, 5, 6]
new_data: list = []
for data in request_data:
    if data <= 5:
        new_data.append(data)
print(new_data)

new_data: list = [data for data in request_data if data <= 5]
print(new_data)

request_data: list = [
    {"id": 1, "name": "1"}, 
    {"id": 2, "name": "2"}, 
    {"id": 3, "name": "3"}
]
new_data: list = [data for data in request_data if data.get("id") > 1] # [{'id': 2, 'name': '2'}, {'id': 3, 'name': '3'}]
print(new_data)


lst = [i for i in range(10)]
tup_lst = (i for i in range(10))
# 生成一个可迭代的生成器对象, 获取的值会调用迭代器的__next__()方法: 可以节省内存
print(tup_lst.__next__())
print(tup_lst.__next__())
print(tup_lst.__next__())
print(tup_lst.__next__())
print(tup_lst.__next__())
print(tup_lst.__next__())
print(tup_lst.__next__()) # StopIteration

'''
    生成器函数
        1. 函数内容使用yield代替return, 返回可迭代的生成器对象
        2. 好处：节省内存、速度快
'''
def test1():
    return 10

def test2():
    yield 10
    yield 100
    yield 1000
    yield 10000
    yield 100000


test_num = test2()
print("type test_num", type(test_num))
print(test_num)
print(test_num.__next__())
print(test_num.__next__())
print(test_num.__next__())
print(test_num.__next__())
print(test_num.__next__())


def test3():
    abc: list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    yield abc
    dec: int = 123
    yield dec
    jjjjjj: str = "1dwahihi"
    yield jjjjjj

test_3 = test3()
print("type test3: ", test_3)
print(test_3.__next__())
print(test_3.__next__())
print(test_3.__next__())

# 列表直接改为生成器
il_lst = [1, 2, 3]
_il = iter(il_lst)
print(_il) # <list_iterator object at 0x7faef018fdc0>
print(_il.__next__())
print(_il.__next__())
print(_il.__next__())


# 字典推导式
request_data: dict = {
    "id": 1,
    "name": "1",
    "width": 10000,
    "height": 1000002222,
    "code": 200
}
new_data: dict = {key: value for key, value in request_data.items() if len(key) > 4}
print(new_data) # {'width': 10000, 'height': 1000002222}
